package com.trust.walletcore.example.utils;

import java.io.IOException;

import okhttp3.*;

/**
 * 发送签名后的交易
 * 签名后的交易将作为 字节数组 返回，你需要将其转化为十六进制字符串，并通过 Solana 的 RPC 服务发送到网络。
 */
public class SolanaRpc {

    private static final String RPC_URL = "https://api.devnet.solana.com";  // Solana RPC URL（Devnet）

    public static void broadcastTransaction(String signedTransaction) {
        OkHttpClient client = new OkHttpClient();

        // 请求体：发送签名后的交易
        String json = "{\n" +
                "  \"jsonrpc\": \"2.0\",\n" +
                "  \"id\": 1,\n" +
                "  \"method\": \"sendTransaction\",\n" +
                "  \"params\": [\"" + signedTransaction + "\"]\n" +
                "}";

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);

        // 创建请求
        Request request = new Request.Builder()
                .url(RPC_URL)
                .post(body)
                .build();

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    System.out.println("Transaction sent: " + response.body().string());
                } else {
                    System.err.println("Transaction failed: " + response.body().string());
                }
            }
        });
    }
}

